﻿using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using UIWindows.Commands;
using UIWindows.Tools.Helper;
using UIWindows.UserControls;
using UIWindows.Views.Dialogs;
using UIWindows.GlobalStatics;
using UIWindows.Domains;
using System.Windows.Data;
using UIWindows.Models;
using NewLife.Data;
using NPOI.SS.UserModel;
using System.IO;
using System.Threading;
using XingLucifer.IBase.Enums;
using UIWindows.Enums;
using Kinlo.Entitys;
using System.Windows;
using UIWindows.Services;
using Kinlo.MESDocking;
using System.Windows.Media;

namespace UIWindows.ViewModels
{
    public class ProductionHistoryViewModel : Domains.ViewModelBase, XingLucifer.IBase.IViewStatus
    {

        #region 分页
        private int _displayDataCount;
        /// <summary>
        /// 当前显示的数量
        /// </summary>
        public int DisplayDataCount
        {
            get { return _displayDataCount; }
            set { SetProperty(ref _displayDataCount, value); }
        }

        private int _quiryTotal;
        /// <summary>
        /// 查询出来的数据
        /// </summary>
        public int QuiryTotal
        {
            get { return _quiryTotal; }
            set { SetProperty(ref _quiryTotal, value); }
        }

        /// <summary>
        /// 当前显示的页数
        /// </summary>
        private int _severalPage;

        public int SeveralPage
        {
            get { return _severalPage; }
            set { SetProperty(ref _severalPage, value); }
        }


        private int _totalPage;
        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPage
        {
            get { return _totalPage; }
            set { SetProperty(ref _totalPage, value); }
        }


        private int _pageCount;
        /// <summary>
        /// 每页数量
        /// </summary>
        public int PageCount
        {
            get { return _pageCount; }
            set { SetProperty(ref _pageCount, value); }
        }

        /// <summary>
        /// 每页数量下拉选择
        /// </summary>
        public List<int> PageCountList { get; set; } = new List<int>();
        #endregion

        #region 条件
        private bool _isOutput;
        /// <summary>
        /// 是否出站
        /// </summary>
        public bool IsOutput
        {
            get { return _isOutput; }
            set { SetProperty(ref _isOutput, value); }
        }

        public DateTime StartTime { get; set; }
        public string StartValidatingTime { get; set; }
        public DateTime EndTime { get; set; }
        public string EndValidatingTime { get; set; }
        /// <summary>
        /// 条码
        /// </summary>
        public string Barcode { get; set; }
        /// <summary>
        /// 间隔时间
        /// </summary>
        public int Intervals { get; set; } = 100;
        #endregion

        #region 配置显示项
        public GridView ProductionDataView { get; set; }
        #endregion

        #region 单例
        public DisplayItemsStatic _displayItems;
        #endregion

        #region 删选

        private string _resultTotalValue = "全部";
        /// <summary>
        /// 总结果
        /// </summary>
        public string ResultTotalValue
        {
            get { return _resultTotalValue; }
            set { SetProperty(ref _resultTotalValue, value); }
        }

        private string _resultScanCodeBeforeValue = "全部";
        /// <summary>
        /// 前扫码结果
        /// </summary>
        public string ResultScanCodeBeforeValue
        {
            get { return _resultScanCodeBeforeValue; }
            set { SetProperty(ref _resultScanCodeBeforeValue, value); }
        }
        private string _CCD1ResultValue = "全部";
        /// <summary>
        /// CCD1结果
        /// </summary>
        public string CCD1ResultValue
        {
            get { return _CCD1ResultValue; }
            set { SetProperty(ref _CCD1ResultValue, value); }
        }

        private string _CCD2ResultValue = "全部";
        /// <summary>
        /// CCD2结果
        /// </summary>
        public string CCD2ResultValue
        {
            get { return _CCD2ResultValue; }
            set { SetProperty(ref _CCD2ResultValue, value); }
        }

        private string _resultShortCicuteValue = "全部";
        /// <summary>
        /// 短路测试仪结果
        /// </summary>
        public string ResultShortCicuteValue
        {
            get { return _resultShortCicuteValue; }
            set { SetProperty(ref _resultShortCicuteValue, value); }
        }

        private string _altimetryResultValue = "全部";
        /// <summary>
        /// 测高结果
        /// </summary>
        public string AltimetryResultValue
        {
            get { return _altimetryResultValue; }
            set { SetProperty(ref _altimetryResultValue, value); }
        }




        /// <summary>
        /// 总结果下拉选择
        /// </summary>
        public List<object> ResultTotaList { get; set; } = new List<object>();
        /// <summary>
        /// 前扫码结果下拉选择
        /// </summary>
        public List<object> ResultScanCodeBeforeList { get; set; } = new List<object>();
        /// <summary>
        /// 短路测试仪结果下拉选择
        /// </summary>
        public List<object> ResultShortCicuteList { get; set; } = new List<object>();

        /// <summary>
        /// 测高结果下拉选择
        /// </summary>
        public List<object> AltimetryResultList { get; set; } = new List<object>();

        
        /// <summary>
        /// CCD1结果下拉选择
        /// </summary>
        public List<object> CCD1ResultList { get; set; } = new List<object>();

        
        /// <summary>
        /// CCD2结果下拉选择
        /// </summary>
        public List<object> CCD2ResultList { get; set; } = new List<object>();




        #endregion
        public AsyncObservableCollection<object> WeightList { get; set; }

        public ProductionHistoryViewModel(DisplayItemsStatic displayItems)
        {
            //ResultTotaList.Add("全部");
            //ResultTotaList.AddRange(Enum.GetValues(typeof(ResultTypes)).Cast<object>());
            ResultTotaList.AddRange(new List<object> {
                "全部",
                ResultTypes.合格,
                ResultTypes.扫码失败,
                ResultTypes.测高NG,
                ResultTypes.短路NG,
                ResultTypes._,
            });
            ResultScanCodeBeforeList.AddRange(new List<object> {
                "全部",
                ResultTypes.合格,
                ResultTypes.扫码失败,
                ResultTypes._,
            });

            CCD1ResultList.AddRange(new List<object> {
                "全部",
                ResultTypes.合格,
                ResultTypes.CCD1NG,
                ResultTypes._,
            });
            

            CCD2ResultList.AddRange(new List<object> {
                "全部",
                ResultTypes.合格,
                ResultTypes.CCD2NG,
                ResultTypes._,
            });


            ResultShortCicuteList.AddRange(new List<object> {
                "全部",
                ResultTypes.合格,
                ResultTypes.短路NG,
                 ResultTypes._,

            });


            AltimetryResultList.AddRange(new List<object> {
                "全部",
                ResultTypes.合格,
                ResultTypes.测高NG,
                 ResultTypes._,
            });


            PageCountList.AddRange(new List<int>
            {
                10,
                50,
                100,
                120,
                200,
                500,
                1000
            });


            _displayItems = displayItems;
            WeightList = new AsyncObservableCollection<object>();
            StartTime = DateTime.Now.Date;
            //StartTime = "2023/07/1".ToDateTime();
            StartValidatingTime = "00:00:00";
            //EndTime = "2023/07/5".ToDateTime();
            EndTime = DateTime.Now.Date;
            EndValidatingTime = "23:59:59";
            SeveralPage = 1;
            DisplayDataCount = 0;
            TotalPage = 1;
            PageCount = 50;
            QuiryTotal = 0;
            ProductionDataView = new GridView();
            Task.Run(() =>
            {
                DateTime time_stat = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0, 0);
                if (DateTime.Now.Hour < 1) { time_stat = time_stat.AddDays(-1); }
                while (true)
                {
                    if (TimeInterval(time_stat))
                    {
                        ProductionData.Meta.TableName = $"ProductionData_{time_stat:yyyy}{time_stat.GetQuarterly()}";
                        long startTime = SnowflakeManager.GetTimeId(new DateTime(time_stat.Year, time_stat.Month, time_stat.Day, 0, 0, 0, 0, DateTimeKind.Local));
                        DateTime end_Time = StartTime.AddDays(1);
                        long endTime = SnowflakeManager.GetTimeId(new DateTime(end_Time.Year, end_Time.Month, end_Time.Day, 0, 0, 0, 0, DateTimeKind.Local));
                        XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId < endTime;
                        if (ExportHelper.Export_ProductionData_xls($".\\TableData\\注液数据{DateTime.Now:yyyy_MM_dd_HH}.xls", expression, _displayItems.WeighingDisplayItems))
                        {
                            "定时导出完成".RunLog(MessageLevelType.信息);
                        }
                        else
                        {
                            "定时导出失败".RunLog(MessageLevelType.信息);
                        }
                        time_stat = time_stat.AddDays(1);
                    }
                    Thread.Sleep(5000);
                }
            });
        }

        private bool TimeInterval(DateTime dateTime) => ((DateTime.Now.Day - dateTime.Day) == 1) && (DateTime.Now.Hour == 1);

        /// <summary>
        /// 上一页
        /// </summary>
        public DelegateCommand PreviousPage => new DelegateCommand(() =>
        {
            if (SeveralPage - 1 > 0)
            {
                WeightList.Clear();
                SeveralPage -= 1;
                Quiry();
            }
        });

        /// <summary>
        /// 下一页
        /// </summary>
        public DelegateCommand NextPage => new DelegateCommand(() =>
        {
            if ((SeveralPage + 1) <= TotalPage)
            {
                WeightList.Clear();
                SeveralPage += 1;
                Quiry();
            }
        });

        /// <summary>
        /// 数据查询
        /// </summary>
        public DelegateCommand QueryData => new DelegateCommand(() =>
        {
            if (StartTime.Year != EndTime.Year)
            {
                "请选择相同年份".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            if (StartTime.GetQuarterly() != EndTime.GetQuarterly())
            {
                $"请选择季度内查询\r\n1月至3月为一个季度\r\n4月至6月为一个季度\r\n7月至9月为一个季度\r\n10月至12月为一个季度\r\n".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            SeveralPage = 1;
            DisplayDataCount = 0;
            TotalPage = 1;
            QuiryTotal = 0;
            WeightList.Clear();
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
            Quiry();
        });


        public DelegateCommand ExportData => new DelegateCommand(() =>
        {
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.Title = "选择保存路径";
            saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|CSV文件(*.csv)|*.csv";
            //saveFileDialog.Filter = "CSV文件(*.csv)|*.csv|Excel文件(*.xls)|*.xls"; 
            saveFileDialog.FilterIndex = 1;

            // Set default file name
            saveFileDialog.FileName = $"注液数据{DateTime.Now:yyyy_MM_dd_HH_mm_ss}";

            if (saveFileDialog.ShowDialog() == true)
            {
                string path = saveFileDialog.FileName;
                string extension = System.IO.Path.GetExtension(path);

                _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

                Task.Run(() =>
                {

                    XCode.Expression expression = CreateTimeRangeExpression();

                    if (!string.IsNullOrEmpty(Barcode))
                    {
                        var str_barcode = Barcode.Split("\r\n");
                        XCode.Expression barcode_expression = ProductionData._.BarCode.Contains(str_barcode[0]);
                        for (int i = 1; i < str_barcode.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(str_barcode[i]))
                            {
                                barcode_expression |= ProductionData._.BarCode.Contains(str_barcode[i]);
                            }
                        }
                        expression &= (barcode_expression);
                    }

                    if (extension.Equals(".xls", StringComparison.OrdinalIgnoreCase))
                    {
                        if (ExportHelper.Export_ProductionData_xls(path, expression, _displayItems.WeighingDisplayItems))
                        {
                            "导出完成".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
                        }
                        else
                        {
                            "导出失败".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                        }
                    }
                    else if (extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                    {
                        if (ExportHelper.Export_ProductionData_xlsx(path, expression, _displayItems.WeighingDisplayItems))
                        {
                            "导出完成".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
                        }
                        else
                        {
                            "导出失败".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                        }
                    }
                    else if (extension.Equals(".csv", StringComparison.OrdinalIgnoreCase))
                    {
                        if (ExportHelper.Export_ProductionData_CSV(path, expression, _displayItems.WeighingDisplayItems))
                        {
                            "导出完成".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
                        }
                        else
                        {
                            "导出失败".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                        }
                    }
                    else
                    {
                        "不支持的文件格式".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                    }
                });
            }
        });
        public DelegateCommand<ProductionData> MouseDoubleClick => new DelegateCommand<ProductionData>(sender =>
        {
            if (sender != null) { return; }

        });

        public DelegateCommand<ListView> SelectUpdata => new DelegateCommand<ListView>(async sender =>
        {

        });
        public DelegateCommand<ListView> SelectInputAndOutputUpdata => new DelegateCommand<ListView>(async sender =>
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }

        });

        private void Quiry()
        {
            _ = Task.Run(() =>
            {
                try
                {
                    PageParameter page = new PageParameter() { PageSize = PageCount, PageIndex = SeveralPage };
                    if ((TotalPage == 1 || TotalPage == 0) && string.IsNullOrEmpty(Barcode))
                    {
                        page.RetrieveTotalCount = true;
                    }
                    else
                    {
                        page.TotalCount = QuiryTotal;
                    }
                    //ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
                    //string[] stime = StartValidatingTime.Split(':');
                    //string[] etime = EndValidatingTime.Split(':');
                    //long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
                    //long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
                    //XCode.Expression expression = expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;
                    XCode.Expression expression = CreateTimeRangeExpression();

                    //if (IsOutput)
                    //    expression &= ProductionData._.ResultOutput != 1;

                    if (!string.IsNullOrEmpty(Barcode))
                    {
                        var str_barcode = Barcode.Split("\r\n");
                        XCode.Expression barcode_expression = ProductionData._.BarCode.Contains(str_barcode[0]);
                        for (int i = 1; i < str_barcode.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(str_barcode[i]))
                            {
                                barcode_expression |= ProductionData._.BarCode.Contains(str_barcode[i]);
                            }
                        }
                        expression &= (barcode_expression);
                    }

                    var list = ProductionData.FindAll(expression, page);
                    foreach (var item in list)
                    {
                        WeightList.Add(item);
                    }
                    if ((TotalPage == 1 || TotalPage == 0) && string.IsNullOrEmpty(Barcode))
                    {
                        TotalPage = (int)page.PageCount;
                    }
                    DisplayDataCount = list.Count();
                    QuiryTotal = (int)page.TotalCount;
                }
                catch (Exception ex)
                {
                    $"历史数据查询异常：{ex}".RunLog(MessageLevelType.警告);
                }
            }).ContinueWith(x =>
            {
                ThreadHelper.CrossThread(sender =>
                {
                    if (DialogHost.IsDialogOpen(PopUpTypes.Global.ToString()))
                    {
                        DialogHost.Close(PopUpTypes.Global.ToString());
                    }
                }, string.Empty);
            }).ConfigureAwait(false);
        }

        public void Load()
        {
            if (!_displayItems.IsDataUpdate)
            {
                return;
            }
            ProductionDataView.Columns.Clear();
            List<DisplayItemsModel> list = new List<DisplayItemsModel>(_displayItems.WeighingDisplayItems);
            list.Sort((x, y) => x.CompareTo(y));
            foreach (var item in list)
            {
                if (item.IsDisplay)
                {
                    var gvc = new GridViewColumn()
                    {
                        DisplayMemberBinding = new Binding()
                        {
                            Path = new System.Windows.PropertyPath(item.Name),
                        },
                        Header = item.Description,
                    };
                    switch (item.DataType)
                    {
                        case "浮点型":
                            gvc.DisplayMemberBinding.StringFormat = "F2";
                            break;
                        case "时间型":
                            gvc.DisplayMemberBinding.StringFormat = "yyyy-MM-dd HH:mm:ss";
                            (gvc.DisplayMemberBinding as Binding).Converter = new Tools.Converter.TimeStampToDateTimeStringConverter();
                            break;
                    }
                    ProductionDataView.Columns.Add(gvc);
                }
            }
            _displayItems.IsDataUpdate = false;
        }

        public void UnLoad()
        {
        }

        //public XCode.Expression CreateTimeRangeExpression()
        //{
        //    ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
        //    string[] stime = StartValidatingTime.Split(':');
        //    string[] etime = EndValidatingTime.Split(':');
        //    long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
        //    long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
        //    XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;

        //    expression &= GenerateExpression(ResultTotalValue, ProductionData._.ResultTotal);
        //    expression &= GenerateExpression(ResultScanCodeBeforeValue, ProductionData._.ResultScanCodeBefore);
        //    expression &= GenerateExpression(ResultShortCicuteValue, ProductionData._.ResultShortCicute);
        //    expression &= GenerateExpression(ResultFormerWeighingValue, ProductionData._.ResultFormerWeighing);
        //    expression &= GenerateExpression(ResultAfterWeighingValue, ProductionData._.ResultAfterWeighing);
        //    expression &= GenerateExpression(ResultRefillWeighingValue, ProductionData._.ResultRefillWeighing);
        //    expression &= GenerateExpression(LeakResultValue, ProductionData._.LeakResult);

        //    return expression;
        //}

        //private XCode.Expression GenerateExpression(string value, XCode.Configuration.Field target)
        //{
        //    if (value != "全部")
        //    {
        //        ResultTypes enumValue;
        //        if (Enum.TryParse(value, out enumValue))
        //        {
        //            return target == enumValue;
        //        }
        //    }
        //    return null;
        //}
        public XCode.Expression CreateTimeRangeExpression()
        {
            ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
            string[] stime = StartValidatingTime.Split(':');
            string[] etime = EndValidatingTime.Split(':');
            long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
            long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));

            // 创建基础时间范围条件
            XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;

            #region 添加筛选条件
            // 定义处理 ResultTypes 属性的委托
            Action<string, XCode.Configuration.Field> processResultType = (resultValue, propertySelector) =>
            {
                if (resultValue != "全部" && Enum.TryParse(resultValue, out ResultTypes enumValue))
                {
                    XCode.Expression _expression = propertySelector == enumValue;
                    expression &= (_expression);
                }
            };

            // 使用委托处理不同的 ResultTypes 属性
            processResultType(ResultTotalValue, ProductionData._.ResultTotal);
            processResultType(ResultScanCodeBeforeValue, ProductionData._.ResultScanCodeBefore);

            processResultType(CCD1ResultValue, ProductionData._.ResultCCD1);
            processResultType(CCD2ResultValue, ProductionData._.ResultCCD2);


            processResultType(ResultShortCicuteValue, ProductionData._.ResultShortCicute);
            processResultType(AltimetryResultValue, ProductionData._.AltimetryResult);


            #endregion

            return expression;
        }


    
         
    }


}
